package com.msh.starter.captcha.bean;

import com.msh.frame.interfaces.IQuestionAnswerGen;
import com.msh.starter.captcha.consts.CaptchaArrayConst;
import com.msh.starter.captcha.enums.CaptchaCharEnum;
import com.msh.starter.captcha.util.CaptchaUtil;

public class RandomCharCaptchaGen  implements IQuestionAnswerGen {
  /**
   * 验证码字符默认长度
   */
  private int length;
  /**
   * 验证码类型
   */
  protected CaptchaCharEnum type;

  public RandomCharCaptchaGen(int length, CaptchaCharEnum type) {
    this.length = length;
    this.type = type;
  }

  public RandomCharCaptchaGen(int length) {
    this.length = length;
    this.type = CaptchaCharEnum.NUMBER;
  }

  @Override
  public QuestionAnswer gen() {
    String random = random();
    return new QuestionAnswer(random, random);
  }

  private String random(){
    char[] codes = new char[length];
    for(int i=0;i<codes.length;i++){
      switch (type){
        case WORD:
          codes[i] = CaptchaArrayConst.EN_MIX[CaptchaUtil.nextInt(CaptchaArrayConst.EN_MIX.length)];
          break;
        case WORD_LOWER:
          codes[i] = CaptchaArrayConst.EN_LOWER[CaptchaUtil.nextInt(CaptchaArrayConst.EN_LOWER.length)];
          break;
        case WORD_UPPER:
          codes[i] = CaptchaArrayConst.EN_UPPER[CaptchaUtil.nextInt(CaptchaArrayConst.EN_UPPER.length)];
          break;
        case WORD_NUMBER_LOWER:
          codes[i] = CaptchaArrayConst.NUM_EN_MIX_LOWER[CaptchaUtil.nextInt(CaptchaArrayConst.NUM_EN_MIX_LOWER.length)];
          break;
        case WORD_NUMBER_UPPER:
          codes[i] = CaptchaArrayConst.NUM_EN_MIX_UPPER[CaptchaUtil.nextInt(CaptchaArrayConst.NUM_EN_MIX_UPPER.length)];
          break;
        case NUMBER:
          codes[i] = CaptchaArrayConst.NUM_ARABIC[CaptchaUtil.nextInt(CaptchaArrayConst.NUM_ARABIC.length)];
          break;
        case NUMBER_ZH_CN:
          codes[i] = CaptchaArrayConst.NUM_ZH_CN[CaptchaUtil.nextInt(CaptchaArrayConst.NUM_ZH_CN.length)];
          break;
        case NUMBER_ZH_HK:
          codes[i] = CaptchaArrayConst.NUM_ZH_HK[CaptchaUtil.nextInt(CaptchaArrayConst.NUM_ZH_HK.length)];
          break;
        case CHINESE:
          codes[i] = CaptchaArrayConst.MODERN_CHINESE[CaptchaUtil.nextInt(CaptchaArrayConst.MODERN_CHINESE.length)];
          break;
        default: codes[i] = CaptchaUtil.nextChar();
      }
    }
    return String.valueOf(codes);
  }
}
